#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "String.h"

String *string_new ()
{
    String *sp;
    char *buf;

    sp = (String *)malloc (sizeof(String));
    if (sp == NULL)
        return NULL;

    buf = (char *)malloc (BUFFERLEN);
    if (buf == NULL)
        return NULL;
    memset (buf, 0, BUFFERLEN);
    buf[0] = 'x';

    sp->buf = buf;
    sp->len = 0;
    sp->max = BUFFERLEN;

    return sp;
}

void string_del (String *s)
{
    if (s == NULL)
        return;
    free (s->buf);
    free (s);
}

void string_add (String *base, char *s)
{
    int slen;

    if (base == NULL)
        return;
    slen = strlen (s);
    if (base->len+slen >= base->max) {
        int newmax = (base->len+slen+1)*2;
        base->buf = (char *)realloc (base->buf, newmax);
        base->max = newmax;
    }
    base->buf = strcat (base->buf, s);
    base->len += slen;
}

void string_put (String *base, char *s)
{
    int slen;

    if (base == NULL)
        return;
    slen = strlen (s);
    if (slen >= base->max) {
        int newmax = (slen+1)*2;
        base->buf = (char *)realloc(base->buf, newmax);
        base->max = newmax;
    }
    base->len = slen;
    strcpy (base->buf, s);
}

void string_reset (String *s)
{
    string_del (s);
    s = string_new ();
}
